const hash = require('hash.js');
module.exports = app => {
    const apiBase = '/_api/health';
    class ProxyController extends app.Controller {
        async proxyHealthPortal(ctx) {
            const target = ctx.url.slice(apiBase.length);
            await ctx.api.doctor.proxy(target);
        }

        async proxyPortalApiWithBody(ctx) {
            const body = await ctx.parseBody();
            this.ctx.body = await ctx.api.doctor.requestWithFormBody(
                this.ctx.method,
                this.ctx.url.substr(apiBase.length),
                body,
            );
        }

        async proxyPortalApiWithoutBody(ctx) {
            this.ctx.body = await ctx.api.doctor.requestWithoutBody(
                this.ctx.method,
                this.ctx.url.substr(apiBase.length),
            );
        }

        numberOrNull(val) {
            if (val === null || val === undefined || val === '') {
                return null;
            }
            const num = Number(val);
            if (Number.isNaN(num)) {
                return null;
            }
            return num;
        }

        async updatephysicalExamination(ctx) {
            let body = await ctx.parseBody();
            const { smok, isExercise, drink,
                appetite, height, weight, waistline, heartRate, SBP, DBP, FBG,
                PBG, LDL, dailyWork, sleep, snore, constipation,
                nutrition, HBALC, TG, TCHO, HDL, Scr, scrUnit,
                uricAcid, Hcy, ALT, AST, serumNa, serumKalium, MAU, picUrls,
            } = body;
            if (picUrls) {
                body = {
                    ...body,
                    picUrls: JSON.parse(picUrls),
                }
            }
            body = {
                ...body,
                smok: smok ? this.numberOrNull(smok) : null,
                isExercise: isExercise ? this.numberOrNull(isExercise) : null,
                drink: drink ? this.numberOrNull(drink) : null,
                appetite: appetite ? this.numberOrNull(appetite) : null,
                height: height ? this.numberOrNull(height) : null,
                weight: weight ? this.numberOrNull(weight) : null,
                waistline: waistline ? this.numberOrNull(waistline) : null,
                heartRate: heartRate ? this.numberOrNull(heartRate) : null,
                SBP: SBP ? this.numberOrNull(SBP) : null,
                DBP: DBP ? this.numberOrNull(DBP) : null,
                FBG: FBG ? this.numberOrNull(FBG) : null,
                PBG: PBG ? this.numberOrNull(PBG) : null,
                LDL: LDL ? this.numberOrNull(LDL) : null,
                dailyWork: dailyWork ? this.numberOrNull(dailyWork) : null,
                sleep: sleep ? this.numberOrNull(sleep) : null,
                snore: snore ? this.numberOrNull(snore) : null,
                constipation: constipation ? this.numberOrNull(constipation) : null,
                nutrition: nutrition ? this.numberOrNull(nutrition) : null,
                HBALC: HBALC ? this.numberOrNull(HBALC) : null,
                TG: TG ? this.numberOrNull(TG) : null,
                TCHO: TCHO ? this.numberOrNull(TCHO) : null,
                HDL: HDL ? this.numberOrNull(HDL) : null,
                Scr: Scr ? this.numberOrNull(Scr) : null,
                scrUnit: scrUnit ? this.numberOrNull(scrUnit) : null,
                uricAcid: uricAcid ? this.numberOrNull(uricAcid) : null,
                Hcy: Hcy ? this.numberOrNull(Hcy) : null,
                ALT: ALT ? this.numberOrNull(ALT) : null,
                AST: AST ? this.numberOrNull(AST) : null,
                serumNa: serumNa ? this.numberOrNull(serumNa) : null,
                serumKalium: serumKalium ? this.numberOrNull(serumKalium) : null,
                MAU: MAU ? this.numberOrNull(MAU) : null,
            }
            const data = await ctx.api.doctorJson.requestWithFormBody(
                this.ctx.method,
                this.ctx.url.substr(apiBase.length),
                body,
            );
            this.ctx.body = {
                code: 0, data
            }
        }
        async physicalExamination(ctx) {
            let body = await ctx.parseBody();
            if (body.picUrls) {
                body.picUrls = JSON.parse(body.picUrls);
            }
            const data = await ctx.api.doctorJson.requestWithFormBody(
                this.ctx.method,
                this.ctx.url.substr(apiBase.length),
                body,
            );
            this.ctx.body = {
                code: 0,
                data: data
            }
        }

        async updateChronicDiseases(ctx) {
            let body = await ctx.parseBody();
            let { chronicDiseases, homeMedicalHistories } = body;
            chronicDiseases = JSON.parse(chronicDiseases);
            homeMedicalHistories = JSON.parse(homeMedicalHistories);
            body = {
                ...body,
                chronicDiseases,
                homeMedicalHistories
            };
            const data = await ctx.api.doctorJson.requestWithFormBody(
                this.ctx.method,
                this.ctx.url.substr(apiBase.length),
                body,
            );
            this.ctx.body = {
                code: 0,
                data: data
            }
        }
        async deleteChronicDiseases(ctx) {
            let body = await ctx.parseBody();
            let { chronicDiseases, homeMedicalHistories } = body;
            if (chronicDiseases) {
                chronicDiseases = JSON.parse(chronicDiseases);
            }
            if (homeMedicalHistories) {
                homeMedicalHistories = JSON.parse(homeMedicalHistories);
            }
            await ctx.api.doctorJson.requestWithFormBody(
                'DELETE',
                `/patient/${this.ctx.params.patientId}/chronic_disease`,
                { chronicDiseases, homeMedicalHistories },
            );
            this.ctx.body = { code: 0, message: "OK", data: null }
        }

        async proxyPortalJsonApiWithoutBody(ctx) {
            this.ctx.body = await ctx.api.doctor.requestWithoutBody(
                this.ctx.method,
                this.ctx.url.substr(apiBase.length),
            );
        }

        async uploadConfig() {
            const { accessKeyId, accessKeySecret, bucket, region, prefix } = this.config.oss;
            const url = `https://${bucket}.${region}.aliyuncs.com`;
            const limit = 1024 * 1024 * 10;
            const expirationDate = new Date(Date.now() + 60 * 1000); // 1 minute available
            const policyObject = {
                expiration: expirationDate.toISOString(),
                conditions: [
                    ["content-length-range", 0, limit], //10m limit
                    ["starts-with", "$key", prefix]
                ]
            };

            const policy = new Buffer(JSON.stringify(policyObject)).toString('base64');
            const signatureData = hash.hmac(hash.sha1, accessKeySecret).update(policy).digest();
            const signature = new Buffer(signatureData).toString('base64');
            this.ctx.body = {
                code: 0,
                data: {
                    limit,
                    accessid: accessKeyId,
                    dir: prefix,
                    expire: expirationDate.valueOf() / 1000,
                    host: url,
                    policy,
                    signature
                }
            }
        }
    }
    return ProxyController;
};
